# !/usr/bin/env python3
# -*- coding: utf-8 -*-
import pymysql.cursors


class MysqlHandlerSub(object):
    def __init__(self):
        self.db = pymysql.connect(host="localhost", user="root", passwd="root", db="codespider", charset="utf8", cursorclass=pymysql.cursors.DictCursor)

    # 第一个参数：1-插入一个省数据；2-市数据；3-区数据；4-乡镇街道数据
    # 第二个参数：省市区街道名称
    # 第三个参数：上级的id，注意省没有上级id
    # 第四个参数：市区街道的12位行政区划编码
    def insert(self, level, area_name, area_code,parent_code, parent_id):
        try:
            with self.db.cursor() as cursor:
                if level == 1:
                    cursor.execute('INSERT INTO area_code_c (area_name, area_code, parent_code, parent_id,level) VALUES (%s,%s,%s,%s,%s)'
                                   , [area_name, area_code,parent_code, parent_id,level])
                elif level == 2:
                    cursor.execute('INSERT INTO area_code_c (area_name, area_code,parent_code, parent_id,level) VALUES (%s, %s,%s,%s, %s)'
                                   , [area_name, area_code,parent_code, parent_id,level])
                elif level == 3:
                    cursor.execute('INSERT INTO area_code_c (area_name, area_code,parent_code, parent_id,level) VALUES (%s, %s, %s,%s, %s)'
                                   '', [area_name, area_code,parent_code, parent_id,level])
                elif level == 4:
                    cursor.execute('INSERT INTO area_code_c (area_name, area_code,parent_code, parent_id,level) VALUES (%s, %s, %s, %s, %s)'
                                   '', [area_name, area_code,parent_code, parent_id,level])
                else:
                     cursor.execute('INSERT INTO area_code_c (area_name, area_code,parent_code, parent_id,level) VALUES (%s,%s, %s,%s, %s)'
                                   , [area_name, area_code,parent_code, parent_id,5])
            insert_id = cursor.lastrowid
            self.db.commit()
        except Exception as e:
            raise Exception('MySQL ERROR:', e)
        # 返回存储后的id
        return insert_id

    #最后需要调用该方法来关闭连接
    def close(self):
        self.db.close()